package com.itheima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDTO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.mededia.pojo.WmMaterial;
import com.heima.model.common.mededia.pojo.WmNewsMaterial;
import com.heima.model.common.mededia.pojo.WmUser;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.itheima.common.exception.CustException;
import com.itheima.file.service.FileStorageService;
import com.itheima.wemedia.mapper.WmMaterialMapper;
import com.itheima.wemedia.mapper.WmNewsMaterialMapper;
import com.itheima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile==null ||  multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }
        // 2 从当前线程取出用户id
        WmUser user = WmThreadLocalUtils.getUser();
        System.out.println(user);
        if (user == null ){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        String originalFilename = multipartFile.getOriginalFilename();

        if (!checkFile(originalFilename)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传符合要求的文件");
        }
        // 3 上传到oss中
        String fileName= UUID.randomUUID().toString().replace("-","");//生成文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//取得后缀
        String fileId = null;


        try {
            fileId = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}",fileId);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", ioException);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        //返回到前端
        wmMaterial.setUrl(webSite+fileId);//前端展示需要前缀
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO wmMaterialDTO) {
        //1 校验参数
        if (wmMaterialDTO == null ){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDTO.checkParam();

        //2 何种查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if (wmMaterialDTO.getIsCollection()!= null && wmMaterialDTO.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,wmMaterialDTO.getIsCollection());
        }
        //必须是当前登录用户的素材
        Integer id = WmThreadLocalUtils.getUser().getId();
        wrapper.eq(WmMaterial::getUserId,id);
        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> iPage = new Page<>(wmMaterialDTO.getPage(), wmMaterialDTO.getSize());
        IPage<WmMaterial> pageResult = page(iPage, wrapper);
        List<WmMaterial> list = pageResult.getRecords();
        for (WmMaterial wmMaterial : list) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }
        //封装对象
        return new PageResponseResult(wmMaterialDTO.getPage(),wmMaterialDTO.getSize(),pageResult.getTotal(),list);
    }

    @Override
    public ResponseResult delete(Integer id) {
        //校验参数
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //业务处理  如果当前素材被引用不可删除
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,wmMaterial.getId());
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材被引用不能删除");
        }//出现在新闻和素材中间表说明被引用不可删除
        // 删除素材库
        removeById(id);
        //删除oss图片
        fileStorageService.delete(wmMaterial.getUrl());
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult collectOrCancle(Integer id, Short isCollection) {
        //校验参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查数据是否存在
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //修改
        wmMaterial.setIsCollection(isCollection);
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private boolean checkFile(String originalFilename) {
        if (StringUtils.isBlank(originalFilename)){
            return false;
        }
        boolean isAllow = false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        for (String suffix : allowSuffix) {
            if (originalFilename.endsWith(suffix)) {
                isAllow = true;
                break;
            }

        }
        return isAllow;



    }
}
